const { Add, Update, QueryOne, ExecGetOne, Exec_Count, Exec, Query, DelMany, Execsql_Count } = require('../db/dbhelper');
var { init, format } = require('../models/matchset');
var dailyuserModel = require('../models/dailyuser');
var { formatDate, formatDateTime } = require('../libs/common');
var _ = require('underscore');
const logger = require('../libs/log').logger;
var moment = require('moment');
var { formatDateYear, formatDate } = require('../libs/common');

//保存
let education_code = {
  '不限学历': 0,
  '高中以上': 1,
  '中专以上': 2,
  '大专以上': 3,
  '本科以上': 4,
  '研究生以上': 5
};
const matchsetSave = async function (doc) {
  try {
    logger.info('--------matchsetSave----保存,doc', doc);
    let result = {
      code: 0,
      msg: '保存成功'
    };
    if (!doc.pcode) {
      return {
        code: 1,
        msg: '网络错误，请检查网络或刷新页面'
      }
    }
    if (!doc.city) {
      return {
        code: 1,
        msg: '请选择希望TA的城市'
      }
    }
    doc.education_code = education_code[doc.education];
    let pl = await QueryOne('hzz_matchsets', { pcode: doc.pcode }, null);
    logger.info('--------matchsetSave--QueryOne--pl', pl);
     // 获取用户是否推荐人
     let user = await QueryOne('hzz_peoples', { code: doc.pcode }, 'isinviter,grender');
    if (pl) {
      doc.city_count = 1;
      doc.id = pl.id;
      await Update('hzz_matchsets', format(doc));
      pl = await QueryOne('hzz_matchsets', { pcode: doc.pcode }, null);
    } else {
      doc.city_count = 1;
      doc.grender = user.grender=='男'? '女':'男';
      pl = await Add('hzz_matchsets', init(doc));
    }
    logger.info('--------matchsetSave--Add--pl', pl);
   
    if (user && user.isinviter) {
      // 获取后台设置的推荐人搜索次数
      let time = 3;
      let timeset = await QueryOne('hzz_settings', { name: '推荐人搜索次数' });
      if (timeset && timeset.datastr) {
        time = Number(timeset.datastr);
      }
      let stime = time - pl.dailytime;
      if (stime > 0) {
        // 创建推荐人搜索用户列表
        // 获取配置的每日推荐人数
        let setData = await QueryOne('hzz_settings', { name: '每日推荐人数' });
        let dailynum = setData ? Number(setData.datastr) : 3;
        let isdone = await createViterData(doc.pcode, dailynum);
        if (isdone>-1) {
          if(isdone==0){
            result.msg = `匹配到0位用户，今日剩余搜索${stime}次`;
          }else{
            pl.dailytime += 1;
            result.msg = `匹配到${isdone}位用户，今日剩余搜索${stime - 1}次`;
          }
        } else {
          result.msg = `匹配失败，请联系客服`;
        }
      } else if (stime <= 0) {
        result.msg = '匹配失败，今日搜索次数已用完';
      }
    } else {
      result.msg = '已设置成功，明日生效';
    }
    await Update('hzz_matchsets', format(pl));
    return result;
  } catch (error) {
    logger.error('--------matchsetSave----保存异常,error', error);
    return {
      code: 1,
      msg: '匹配异常，请联系客服'
    }
  }
}

//查询详情
const matchsetQueryOne = async function (pcode) {
  try {
    logger.info('matchsetQueryOne---pcode', pcode)
    let obj={
        "pcode": pcode,
       "age": "25-30",
       "height": "175-185",
       "city": "深圳",
       "education": "不限",
       "education_code": 0,
       "marital_status": "未婚",
       "preference": 1,
    }
    let info = await QueryOne('hzz_matchsets', { pcode: pcode }, null);
    let peo = await ExecGetOne(`select isinviter,grender from hzz_peoples where code ='${pcode}'`);
    info = info || obj;
    if(peo){
      info.isinviter = peo.isinviter;
      if(!info.grender){
        info.grender = peo.grender=='男'?'女':'男';
      }
    }
    

    return {
      code: 0,
      data: info
    }
  } catch (error) {
    logger.info('matchsetQueryOne---error', error)
    return {
      code: 1,
      msg: error ? error.message : '查询匹配设置异常'
    }
  }
}

// 获取查询条件
const matchsetFilter = async function (pcode) {
  try {
    let info = await QueryOne('hzz_matchsets', { pcode: pcode });
    let peo = await QueryOne('hzz_peoples', { code: pcode }, 'province,city,area_town,grender,isinviter');
    let filterStr = ' ';
    let sortStr = '';
    let orStr = '';
    let orStr1 = '';
    let orStr2 = '';
    let orStr3 = '';
    let orStr4 = '';
    let filter = {
      grender: peo.grender=='男'?'女':'男',
      city: info ? info.city + '市' : '深圳市',
    };

    filterStr = ` AND city='${filter.city}' `;
    filterStr += ` AND grender='${filter.grender}' `;
    orStr = filterStr;
    // 推荐人根据匹配条件查询--// 性别
    if (info && peo && peo.isinviter && info.grender && info.grender != '不限') {
      filterStr = ` AND grender='${info.grender}' `;
      filterStr += ` AND city='${filter.city}' `;
      orStr = filterStr;
    }

    var toa = await Exec_Count('hzz_peoples', filterStr, pcode);
    if (info && toa > 2) {
      toa = await Exec_Count('hzz_peoples', filterStr, pcode);
      if (toa > 2) {
        // 婚况
        if (info.marital_status && info.marital_status != '不限') {
          filter.marital_status = info.marital_status;
          if (info.marital_status == '未婚') {
            filterStr += ` AND marital_status='未婚' `;
          } else if (info.marital_status == '离异无孩(含未婚)') {
            filterStr += ` AND marital_status IN('未婚','离异无孩') `;
          }
          // filterStr +=` AND marital_status LIKE '%${info.marital_status}%' `;
        }
        toa = await Exec_Count('hzz_peoples', filterStr, pcode);
        if (toa > 2) {
          //年龄
          if (info.age) {
            let ages = info.age.split('-');
            filter.age_min = ages[0];
            filter.age_max = ages[1];
            filterStr += ` AND age>=${filter.age_min} AND age<=${filter.age_max} `;
          }
          toa = await Exec_Count('hzz_peoples', filterStr, pcode);
          if (toa > 2) {
            // 身高
            if (info.height) {
              let heights = info.height.split('-');
              filter.height_min = heights[0];
              filter.height_max = heights[1];
              filterStr += ` AND height>=${filter.height_min} AND height<=${filter.height_max} `;
            }
            toa = await Exec_Count('hzz_peoples', filterStr, pcode);
            if (toa > 2) {
              //学历选项： 高中以上（1）、中专以上（2）、大专以上（3）、本科以上（4）、硕士以上（5）、不限学历（0）
              if (info.education_code) {
                filterStr += ` AND education_code>=${info.education_code} `;
              }
            }
          }
        }
      }
      if (info.marital_status && info.marital_status != '不限') {
        orStr1 += ` marital_status LIKE '%${info.marital_status}%'`
      }
      if (info.age) {
        let ages = info.age.split('-');
        filter.age_min = ages[0];
        filter.age_max = ages[1];
        orStr2 += ` (age>=${filter.age_min} AND age<=${filter.age_max})  `;
      }
      // 身高
      if (info.height) {
        let heights = info.height.split('-');
        filter.height_min = heights[0];
        filter.height_max = heights[1];
        orStr3 += ` (height>=${filter.height_min} AND height<=${filter.height_max}) `;
      }
      //学历选项： 高中以上（1）、中专以上（2）、大专以上（3）、本科以上（4）、硕士以上（5）、不限学历（0）
      if (info.education_code) {
        orStr4 += ` education_code>=${info.education_code} `;
      }

      // 军人优先
      if (info.preference==1) {
        sortStr += ' soldier DESC'
      }
    }
    let orStrs = '';
    let orStrs2 = '';
    if (orStr1) {
      orStrs += ` AND (${orStr1})`;
    }
    if (orStr2) {
        orStrs += ` AND ${orStr2}`;
    }
    if (orStr3) {
      orStrs2 += `  ${orStr3}`;
    }
    if (orStr4) {
      if (orStrs2 == '') {
        orStrs2 += ` ${orStr4}`;
      } else {
        orStrs2 += ` OR ${orStr4}`;
      }
    }
    if (orStrs != '') {
      orStr += orStrs;
    } 
    if(orStrs2 !=''){
      orStr += ' AND ('+orStrs2+')';
    }
    return {
      filterStr: filterStr,
      sortStr: sortStr,
      orStr: orStr,
      grender: info ? info.grender : null
    };
  } catch (error) {
    return '';
  }
}

// 已经推送过的先排除
let omitDay = 1;
async function omitUser(pcode, list, dailynum) {
  // 获取需要排除个数
  let outnum = list.length - dailynum;
  // 取近10日内用户已查看用户数
  const startDate = moment().subtract(10,'day').format('YYYY-MM-DD');
  let userList = await Exec(`select * from hzz_dailyusers where pcode = '${pcode}' AND builddate> '${startDate}' AND isout =1 ORDER BY id DESC `);
  // 依次去移除近期推荐过的
  for (let index = 0; index < userList.length; index++) {
    const user = userList[index];
    if(outnum==0){
      break;
    }
    if(_.contains(list,user.tcode)){
      outnum--;
      list = _.without(list, user.tcode);
    }
  }
  return list;
  // omitDay = Math.floor(list.length/dailynum);
  // // 取近5日推荐人
  // // 最近5日日期
  // let datalist = await Exec(`SELECT DISTINCT builddate  from hzz_dailyusers  WHERE pcode='${pcode}' AND isout =1 ORDER BY createtime DESC LIMIT ${omitDay}`);
  // let old_sql = `select DISTINCT tcode from hzz_dailyusers where pcode='${pcode}' AND isout =1 `;
  // if (datalist.length > 0) {
  //   old_sql += ` AND builddate IN ('${_.compact(_.pluck(datalist, 'builddate')).join("','")}')`
  // }
  // let oldList = await Exec(old_sql);
  // let old_codes = _.compact(_.pluck(oldList, 'tcode'));
  // // 今日已推荐用户单独排除
  // let builddate = formatDate(new Date());
  // let todayUsers = await Exec(`select tcode from hzz_dailyusers  WHERE pcode='${pcode}' AND builddate='${builddate}'`);
  // old_codes = _.compact(old_codes.concat(_.pluck(todayUsers, 'tcode')));
  // let diff = _.difference(list, old_codes);
  return diff;
}
// 今日推荐不足人数的从历史中补
async function omitUserBack(pcode, list, addnum, grender) {
  let datalist = await Exec(`SELECT DISTINCT builddate  from hzz_dailyusers  WHERE pcode='${pcode}' AND isout =1 ORDER BY id DESC LIMIT ${omitDay}`);
  let old_sql = `select code from hzz_peoples where code IN (select DISTINCT tcode from hzz_dailyusers where pcode='${pcode}' AND source='每日推荐'   `;
  if (datalist.length > 0) {
    old_sql += ` AND builddate NOT IN ('${_.compact(_.pluck(datalist, 'builddate')).join("','")}')  ORDER BY id ASC`
  }
  old_sql+= `) AND grender='${grender}'`;
  let oldList = await Exec(old_sql);
  let old_codes = _.unique(_.pluck(oldList, 'tcode'));
  let diff = _.difference(old_codes, list);
  if (diff.length >= addnum) {
    diff = list.concat(diff.splice(0, addnum));
  } else {
    diff = list.concat(diff);
  }
  return diff;
}
// 创建今日推荐用户列表
async function createDailyData(rcodes, pcode, dailynum) {
  let builddate = formatDate(new Date());
  for (let i = 0; i < rcodes.length; i++) {
    let tcode = rcodes[i];
    let ex = await QueryOne('hzz_dailyusers', { pcode: pcode, tcode: tcode, builddate: builddate });
    if (!ex) {
      if (tcode) {
        let dailyObj = {
          pcode: pcode,
          tcode: tcode,
          source: '推荐人搜索',
          dailynum: dailynum,
          isout: 0,
          builddate: builddate,
          createtime: new Date(),
          updatetime: new Date(),
        };
        await Add('hzz_dailyusers', dailyObj);
      }
    }
  }
}
// 创建推荐人搜索用户列表
async function createViterData(pcode,  dailynum) {
  try {
    let mset = await matchsetFilter(pcode);
    logger.info('创建推荐人搜索用户列表---mset,',mset)
    let builddate = formatDate(new Date());
    let sql = `SELECT code FROM hzz_peoples WHERE online=1 AND isopen=0 AND code <>'${pcode}' AND CODE NOT IN (SELECT pcode FROM hzz_uinteresteds WHERE fcode='${pcode}') 
    AND CODE NOT IN (select tcode from hzz_dailyusers  WHERE pcode='${pcode}' AND builddate='${builddate}')`;
    let sql_count = sql + mset.filterStr + ' ORDER BY topstate DESC,sortnum DESC,createtime DESC ';
    logger.info(`-----createViterData----创建推荐人搜索用户列表,,,sql_count`, sql_count)
    let peopleList = await Exec(sql_count);
    let diff = _.pluck(peopleList, 'code');
    logger.info(`-----createViterData----创建推荐人搜索用户列表,,,sql_count---`, diff)
    if(diff.length>dailynum){
      diff = await omitUser(pcode, diff, dailynum);//排除掉已推荐过的用户
    }
    // if(diff.length>6){
    //   diff = await omitUser(pcode, diff);//排除掉近3日推荐过的用户
    // }
    // if (diff.length > 0) {// 如果搜索用户足够，直接创建推荐列表
      if(diff.length>dailynum){
        diff = diff.splice(0, dailynum);
      }
      await createDailyData(diff, pcode, dailynum);
    // } else {
    //   logger.info(`-----createViterData----搜索推荐用户不足${dailynum}人`, pcode)
    //   console.log(`-----createViterData----搜索推荐用户不足${dailynum}人`, pcode)
    //   sql_count = sql + mset.orStr;
    //   logger.info(`-----createViterData----创建推荐人搜索用户列表,,,sql_count22---`, sql_count)
    //   orlist = await Exec(sql_count);
    //   orlist = _.pluck(orlist, 'code');
    //   logger.info(`-----createViterData----创建推荐人搜索用户列表,,,sql_count22---`, orlist)
    //   diff = _.unique(_.compact(diff.concat(orlist)));
    //   diff = await omitUser(pcode, diff);//排除掉近3日推荐过的用户2
    //   logger.info(`-----createViterData----创建推荐人搜索用户列表,,,diff33---`, diff)
    //   if (diff.length >= dailynum) {
    //     diff = diff.splice(0, dailynum);
    //   } else {
    //     let snum = dailynum - diff.length;// 缺失个数
    //     diff = await omitUserBack(pcode, diff, snum, grender);
    //     logger.info(`-----createViterData----创建推荐人搜索用户列表,,,diff44---`, diff)
    //   }
    //   logger.info(`-----dailyDone----每日推荐用户diff`, diff)
    //   await createDailyData(diff, pcode);
    // }
    return diff.length;
  } catch (error) {
    logger.error(`-----createViterData----创建推荐人搜索用户列表，error`, error)
    return -1;
  }
}

async function matchsetUpdate(doc) {
  try {
    logger.info('--------matchsetSave----保存,doc', doc);
    let result = {
      code: 0,
      msg: '保存成功'
    };
    if (!doc.id) {
      return {
        code: 1,
        msg: '缺失参数id'
      }
    }
    if (!doc.city) {
      return {
        code: 1,
        msg: '请选择希望TA的城市'
      }
    }
    doc.education_code = education_code[doc.education];
    logger.info('--------matchsetSave--QueryOne--doc', doc);
    await Update('hzz_matchsets', format(doc));
    return result;
  } catch (error) {
    logger.error('--------matchsetSave----保存异常,error', error);
    return {
      code: 1,
      msg: '保存异常，请联系客服'
    }
  }
}

async function matchsetList(req) {
  try {
    let { userphone, userrole } = req.headers;
    let isenterprise = userrole ? userrole.split(',').includes('enterprise') : false;
    let { name, pagenum, pagesize } = req.body;
    pagenum = pagenum || 1;
    pagesize = pagesize || 5;
    let userlist;
    let invitcode;
    // 如果是外联合作推荐人角色，并且绑定手机号的，只查询自己用户信息
    if(isenterprise && userphone){
      let da1= await ExecGetOne(`select pcode from hzz_inviterhistories where phone ='${userphone}'`);
      if(da1){
        invitcode = da1.pcode;
      }
    }
    let ss_sql=`select code from hzz_peoples where  1=1 `;
    if(invitcode){
      ss_sql+= ` AND invitcode='${invitcode}'`;
    }
    if (name) {
      ss_sql+= ` AND name like'%${name}%'`;
      
    }
    if(name || invitcode){
      let userdata = await Exec(ss_sql);
      userlist = _.pluck(userdata, 'code').join("','");
    }
    let sql = `SELECT * FROM hzz_matchsets  WHERE length(pcode)=12`;
    let sql_filter='';
    if (userlist) {
      sql_filter += `  AND pcode IN ('${userlist}') `
    }
    sql += sql_filter;
    sql += ' ORDER BY updatetime DESC,id ASC ';
    sql += ` LIMIT ${(pagenum - 1) * pagesize}, ${pagesize}; `
    let listData = await Exec(sql);
    let peos = [];
    let list = [];
    if (listData && listData.length) {
      let codestr = _.compact(_.pluck(listData, 'pcode')).join("','");
      let execsql = `SELECT name,nickname,name_father,identity,code FROM hzz_peoples WHERE CODE IN ('${codestr}')`;
      peos = await Exec(execsql);
    }
    listData = _.map(listData, function (item) {
      let people = _.find(peos, function (po) {
        return po.code == item.pcode;
      })
      if (people) {
        if (people.identity == '家长') {
          item.name = people.name_father;
        } else {
          item.name = people.name;
        }
        item.nickname = people.nickname;
      }
      item.updatetime = formatDateTime(item.updatetime);
      delete item.createtime;
      return item;
    });

    let total = await Execsql_Count(`SELECT count(1) as total FROM hzz_matchsets  WHERE length(pcode)=12 `+ sql_filter);
    let pagecount = Math.ceil(total / pagesize);
    return {
      code: 0,
      data: {
        list: listData,
        total,
        pagecount
      },
      msg: '获取成功'
    }
  } catch (error) {
    return {
      code: 1,
      msg: error ? error.message : '获取异常'
    }
  }
}

module.exports = {
  matchsetSave,
  matchsetQueryOne,
  matchsetFilter,
  matchsetUpdate,
  matchsetList
}